<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form" v-if="headerShow">
        <a-form size="small" :model="pageData" layout="inline" :label-col-props="{ span: 11 }"
          :wrapper-col-props="{ span: 13 }">
          <a-form-item :style="{ width: '280px' }" label-col-flex="100px" label="记录单号" field="recordCode">
            <a-input allow-clear class="bacClass" v-model="pageData.recordCode" @blur="inputBlur" @press-enter="huiche" />
          </a-form-item>

          <!-- <a-form-item :style="{ width: '250px' }" label="供应商编号" field="supplierCode" @press-enter="huiche">
                                                                            <a-select popup-container="html"  class="bacClass" :loading="loading" @search="handleSearch"
                                                                                        v-model="pageData.supplierCode" :filter-option="false" allow-search allow-clear
                                                                                        @focus="focusSel1" @change="changeCose">
                                                                                        <a-option v-for="item in pageData.DefectNameList1" :value="item['supplierCode']">{{
                                                                                            item["supplierCode"]
                                                                                        }}
                                                                                        </a-option>
                                                                                    </a-select>
                                                                            <a-input class="bacClass" placeholder="" v-model="pageData.supplierCode"
                                                                                @press-enter="huiche" />
                                                                            <a-input class="bacClass" placeholder="请输入代号" v-model="pageData.supplierCode" />
                                                                        </a-form-item> -->

          <a-form-item :style="{ width: '280px' }" label-col-flex="100px" label="供应商名称" field="supplierName">
            <a-input allow-clear v-model="pageData.supplierName" class="bacClass" @press-enter="huiche" />
          </a-form-item>

          <a-form-item :style="{ width: '280px' }" label-col-flex="100px" label="原料编码" field="rawCode">
            <!-- <a-select popup-container="html"  class="bacClass" :loading="loading" @search="handleSearch"
                                                                                        v-model="pageData.rawCode" :filter-option="false" allow-search allow-clear
                                                                                        @focus="focusSel">
                                                                                        <a-option v-for="item in pageData.DefectNameList" :value="item['rawCode']">{{
                                                                                            item["rawCode"]
                                                                                        }}
                                                                                        </a-option>
                                                                                    </a-select> -->
            <!-- <a-input class="bacClass" placeholder="请输入代号" v-model="pageData.rawCode" /> -->
            <a-input allow-clear class="bacClass" placeholder="" v-model="pageData.rawCode" @press-enter="huiche" />
          </a-form-item>

          <a-form-item :style="{ width: '280px' }" label-col-flex="100px" label="原料名称" field="rawName">
            <a-input class="bacClass" v-model="pageData.rawName" @press-enter="huiche" allow-clear />
          </a-form-item>

          <a-form-item :style="{ width: '280px' }" label-col-flex="100px" label="纱牌" field="yarnCard">
            <a-input class="bacClass" v-model="pageData.yarnCard" @press-enter="huiche" allow-clear />
          </a-form-item>

          <a-form-item :style="{ width: '280px' }" label-col-flex="100px" label="色号" field="colourNumber">
            <a-input class="bacClass" v-model="pageData.colourNumber" @press-enter="huiche" allow-clear />
          </a-form-item>

          <a-form-item :style="{ width: '280px' }" label-col-flex="100px" label="色称" field="colorName">
            <a-input class="bacClass" v-model="pageData.colorName" @press-enter="huiche" allow-clear />
          </a-form-item>

          <a-form-item :style="{ width: '280px' }" label-col-flex="100px" label="纱批" field="batch">
            <a-input class="bacClass" v-model="pageData.batch" @press-enter="huiche" allow-clear />
          </a-form-item>

          <!-- <a-form-item label="开单日期"> -->

          <a-form-item :style="{ width: '280px' }" label-col-flex="100px" label="开单开始日期" field="dateStart">
            <a-date-picker  popup-container="html"  class="bacClass" v-model="pageData.dateStart" @press-enter="huiche" />
          </a-form-item>

          <a-form-item :style="{ width: '280px' }" label-col-flex="100px" label="开单结束日期" field="dateEnd">
            <a-date-picker  popup-container="html"  class="bacClass" v-model="pageData.dateEnd" @press-enter="huiche" />
          </a-form-item>

          <!-- <a-range-picker  popup-container="html"  v-model="pageData.billingDate"
                                                                                        style="width: 360px; margin-right: 24px; margin-bottom: 24px;"
                                                                                        />
                                                                                </a-form-item> -->
        </a-form>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18" />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
      <div class="my-tool-bar">
        <div style="text-align: right">
          <Toolbar :items="pageData.btnList" @add="addHandler" @del="deleteHandler" @select="selectHandler"
            @export="exports" @dyBoufei="handleClick">
          </Toolbar>
        </div>
      </div>
    </template>
    <template #pageTabel>
      <!-- <a-table :style="{
                                                                            height: pageData.rHeight1 + 'px'
                                                                        }" :scrollbar="true" sticky-header @page-change="pagination.change" stripe :bordered="true"
                                                                            :columns="tableColumns" :row-selection="{ showCheckedAll: true, width: 50, onlyCurrent: true }"
                                                                            v-model:selected-keys="selectedRowKeys" :loading="pageData.pageLoading" :data="table.dataList"
                                                                            :pagination="false"
                                                                            :rowKey="rowKey" size="mini">
                                                                            <template #action="{ record }">
                                                                                <a-button type="primary" size="small" status="warning" @click="editHandler(record)"
                                                                                    :disabled="!pageData.isEdit">
                                                                                    <template #icon>
                                                                                        <icon-edit />
                                                                                    </template>
                                                                                    修 改
                                                                                </a-button>
                                                                            </template>

                                                                        </a-table> -->
      <a-spin :loading="pageData.pageLoading" tip="加载中" dot style="height: 100%; width: 100%; z-index: 999">
        <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true"
          :suppressDragLeaveHidesColumns="true" rowSelection="multiple" @grid-ready="gridReady" style="height: 100%"
          :defaultColDef="defaultColDef" class="ag-theme-alpine" :rowData="table.dataList" :columnDefs="tc"
          :localeText="localeText1" @columnVisible="onColumnVisible" @columnResized="onColumnResized"
          @columnMoved="onColumnMoved">
        </AgGridVuesCopys>
      </a-spin>
    </template>
    <paginationCopys :total="total" show-total show-jumper show-page-size @change="PageSize" @page-size-change="change1"
      style="justify-content: center" :page-size="pagination.pageSize" :current="pagination.page"
      :page-size-options="pagingList1" />

    <a-drawer style="z-index: 999" ok-text="保存" cancel-text="关闭" :drawer-style="{ zIndex: 999 }" height="100%"
      popup-container="#main-container" :mask-closable="false" :width="400" :visible="pageData.showAdd" unmountOnClose
      @ok="sideOk" @cancel="pageData.showAdd = false" placement="bottom">
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <div>
        <!-- <div style="width: 1540px; overflow: auto" class="scrollbar">
          <el-scrollbar> -->
        <a-form ref="formRef" layout="horizontal" :model="dataForm" :label-col-props="{ span: 11 }"
          :wrapper-col-props="{ span: 13 }" size="small">
          <a-row :gutter="16">
            <a-col :span="6">
              <a-form-item label="选择公司" field="companyId" :rules="[{ required: true, message: '公司必填' }]">
                <a-cascader :options="pageData.corporateList" @change="corporateChange" v-model="dataForm.companyId"
                  allow-clear class="bacClass" ref="corporateRef" :loading="pageData.corporateLoading" popup-container="html"/>
                <!-- </a-select> -->
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="仓库名称" field="warehouseId" :rules="[{ required: true, message: '仓库名称必填' }]"
                :validate-trigger="['change', 'blur']">
                <a-select popup-container="html"  class="bacClass" placeholder="" v-model="dataForm.warehouseId" allow-clear>
                  <a-option v-for="item in whList" :value="item.id">
                    {{ item.warehouseName }}
                  </a-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="仓库编号" field="warehouseId" :rules="[{ required: true, message: '仓库编号必填' }]">
                <a-select popup-container="html"  class="bacClass" placeholder="" v-model="dataForm.warehouseId" allow-clear>
                  <a-option v-for="item in whList" :value="item.id">
                    {{ item.warehouseCode }}
                  </a-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="入库单号" field="sourceOdd" :validate-trigger="['change', 'blur']"
                :rules="[{ required: true, message: '入库单号必填' }]">
                <a-select popup-container="html"  :disabled="dataForm.warehouseId == ''" class="bacClass" @search="handleSearch9"
                  @focus="focusSel9" placeholder="" v-model="dataForm.sourceOdd" allow-clear allow-search
                  @clear="clearsource" @change="changeSoure">
                  <a-option v-for="item in dataForm.nameList" :value="item['inStockNumber']">
                    {{ item['inStockNumber'] }}
                  </a-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="16">
            <a-col :span="6">
              <a-form-item label="原料编号" field="rawCode" :validate-trigger="['change', 'blur']"
                :rules="[{ required: true, message: '原料编号必填' }]">
                <!-- <a-input class="bacClass" v-model="dataForm.rawCode" /> -->
                <a-select popup-container="html"  class="bacClass" :disabled="dataForm.sourceOdd == ''" placeholder="" v-model="dataForm.rawCode"
                  allow-clear allow-search @search="handleSearchp" @focus="focusSelp" @change="changeq1">
                  <a-option v-for="item in dataForm.nameList1" :value="item.yarnCode">
                    {{ item.yarnCode ? item.yarnCode + ' —— ' + item.yarnName : '' }}
                  </a-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="原料名称" field="rawName" :validate-trigger="['change', 'blur']"
                :rules="[{ required: true, message: '原料名称必填' }]">
                <!-- <a-input disabled v-model="dataForm.rawName" /> -->
                <a-select popup-container="html"  class="bacClass" disabled placeholder="" v-model="dataForm.rawName" allow-clear allow-search
                  @search="handleSearchp1" @focus="focusSelp1" @change="changeq2">
                  <a-option v-for="item in dataForm.nameList1" :value="item.yarnName">
                    {{ item.yarnName }}
                  </a-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="纱批">
                <a-input v-model="dataForm.batch" disabled />
                <!-- <a-input v-model="dataForm.objInput.batch" disabled /> -->
                <!-- <a-select popup-container="html"  class="bacClass" @search="handleSearchs" @focus="focusSels" placeholder=""
                                                                                        v-model="dataForm.batch" allow-clear allow-search>
                                                                                        <a-option v-for="item in dataForm.nameList2" :value="item">
                                                                                            {{ item }}
                                                                                        </a-option> -->
                <!-- </a-select> -->
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="记录单号" field="recordCode" :validate-trigger="['change', 'blur']">
                <a-input v-model="dataForm.recordCode" disabled />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="16">
            <a-col :span="6">
              <a-form-item label="供应商名称">
                <!-- <a-input v-model="dataForm.objInput.supplierName" disabled /> -->
                <a-input v-model="dataForm.supplierName" disabled />
              </a-form-item>
            </a-col>

            <a-col :span="6">
              <a-form-item label="纱牌">
                <!-- <a-input v-model="dataForm.objInput.yarnCard" disabled /> -->
                <a-input v-model="dataForm.yarnCard" disabled />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="色号">
                <!-- <a-input v-model="dataForm.objInput.colourNumber" disabled /> -->
                <a-input v-model="dataForm.colourNumber" disabled />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="色称">
                <a-input v-model="dataForm.colorName" disabled />
                <!-- <a-input v-model="dataForm.objInput.colorName" disabled /> -->
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="16">
            <a-col :span="6">
              <a-form-item label="单位">
                <!-- <a-select popup-container="html"  class="bacClass" v-model="dataForm.unit" @search="searchUnit"
                                                                                        @focus="focusunit" allow-clear allow-search :filter-option="false">
                                                                                        <a-option v-for="item in pageData.unitList" :value="item['detailName']">{{
                                                                                            item["detailName"]
                                                                                        }}
                                                                                        </a-option>
                                                                                    </a-select> -->
                <a-input v-model="dataForm.unit" disabled />
                <!-- <a-input v-model="dataForm.objInput.unit" disabled /> -->
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="客户名称">
                <a-input v-model="dataForm.clientName" disabled />
                <!-- <a-input v-model="dataForm.customName" disabled /> -->
              </a-form-item>
            </a-col>
            <!-- <a-col :span="4">
                                                                                <a-form-item label="记帐员" field="bookkeeper" :validate-trigger="['change', 'blur']"
                                                                                    :rules="[{ required: true, message: '记帐员必填' }]">
                                                                                    <a-input class="bacClass" v-model="dataForm.bookkeeper" />
                                                                                </a-form-item>
                                                                            </a-col> -->

            <!-- <a-col :span="4">
                                                                                <a-form-item label="供应商编号" field="supplierCode" :validate-trigger="['change', 'blur']"
                                                                                    :rules="[{ required: true, message: '供应商编号必填' }]">
                                                                                    <a-input class="bacClass" v-model="dataForm.supplierCode" />
                                                                                </a-form-item>
                                                                            </a-col> -->
            <a-col :span="6">
              <a-form-item label="等级">
                <a-input v-model="dataForm.level" disabled />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="载重说明" field="loadExplain" :validate-trigger="['change', 'blur']">
                <a-input class="bacClass" v-model="dataForm.loadExplain" />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
        <a-space style="margin-bottom: 10px">
          <a-button type="primary" @click="addLine" size="mini">新增</a-button>
          <a-button type="primary" status="danger" @click="delLine" size="mini">删除</a-button>
        </a-space>
        <a-table stripe :columns="tableColumnsCf" :row-selection="{ showCheckedAll: true, width: 50 }"
          v-model:selected-keys="s" :loading="table.tableLoading" :data="listOb.list" :rowKey="rowKey" size="mini"
          :bordered="{ cell: true }">
          <template #yarnBallNum="{ record }">
            <div style="width: 100%">
              <a-input-number v-model="record.yarnBallNum" class="input-demo bacClass" :min="0" :max="1000000000"
                style="border-right: 1px solid #dde2eb" :precision="0" />
            </div>
          </template>
          <template #toHeavyKg="{ record }">
            <div style="width: 100%">
              <a-input-number v-model="record.toHeavyKg" class="input-demo" :min="0" :max="1000000000" disabled
                @change="poundChange(record, 1)" style="border-right: 1px solid #dde2eb" :precision="2" />
            </div>
          </template>
          <template #toHeavyPound="{ record }">
            <div style="width: 100%">
              <a-input-number v-model="record.toHeavyPound" class="input-demo" :min="0" :max="1000000000" disabled
                :precision="2" style="border-right: 1px solid #dde2eb" />
            </div>
          </template>
          <template #roughKg="{ record }">
            <div style="width: 100%">
              <a-input-number v-model="record.roughKg" class="input-demo bacClass" :min="0" :max="1000000000"
                @change="poundChange(record, 2)" style="border-right: 1px solid #dde2eb" :precision="2" />
            </div>
          </template>
          <template #roughPound="{ record }">
            <div style="width: 100%">
              <a-input-number v-model="record.roughPound" class="input-demo" :min="0" :max="1000000000" disabled
                :precision="2" style="border-right: 1px solid #dde2eb" />
            </div>
          </template>
          <template #tareKg="{ record }">
            <div style="width: 100%">
              <a-input-number v-model="record.tareKg" class="input-demo bacClass" :min="0" :max="1000000000"
                @change="poundChange(record, 3)" style="border-right: 1px solid #dde2eb" :precision="2" />
            </div>
          </template>
          <template #tarePound="{ record }">
            <div style="width: 100%">
              <a-input-number v-model="record.tarePound" class="input-demo" :min="0" :max="1000000000" disabled
                :precision="2" style="border-right: 1px solid #dde2eb" />
            </div>
          </template>
          <template #suttleKg="{ record }">
            <div style="width: 100%">
              <a-input-number v-model="record.suttleKg" class="input-demo" :min="-9999999999" :max="1000000000" disabled
                @change="poundChange(record, 4)" style="border-right: 1px solid #dde2eb" :precision="2" />
            </div>
          </template>
          <template #suttlePound="{ record }" style="border-right: 1px solid #dde2eb">
            <div style="width: 100%">
              <a-input-number v-model="record.suttlePound" class="input-demo" :min="-999999999999" :max="1000000000"
                disabled :precision="2" style="border-right: 1px solid #dde2eb" />
            </div>
          </template>
          <template #profitKg="{ record }">
            <div style="width: 100%">
              <a-input-number v-model="record.profitKg" class="input-demo" :min="-99999999999" :max="1000000000" disabled
                :precision="2" @change="poundChange(record, 5)" style="
                      border-right: 1px solid #dde2eb;
                      background-color: #00b42a;
                      color: white !important;
                    " :class="{ bacColor: record.profitKg < 0 }" />
            </div>
          </template>
          <template #profitPound="{ record }">
            <div style="width: 100%">
              <a-input-number v-model="record.profitPound" class="input-demo" :min="-99999999" :max="1000000000" disabled
                :precision="2" style="
                      border-right: 1px solid #dde2eb;
                      background-color: #00b42a;
                      color: white !important;
                    " :class="{ bacColor: record.profitPound < 0 }" />
            </div>
          </template>
          <template #eachRemark="{ record }">
            <div style="width: 100%">
              <a-textarea class="bacClass" placeholder="" v-model="record.eachRemark" auto-size :max-length="400"
                allow-clear show-word-limit />
              <!-- <a-input class="bacClass" v-model="record.eachRemark" /> -->
            </div>
          </template>
        </a-table>
        <!-- </el-scrollbar>
        </div> -->
      </div>
    </a-drawer>
    <a-modal v-model:visible="visible" title="纱仓抽磅记录" @cancel="handleCancel" width="1000px">
      <div id="rawmat">
        <div>
          <div style="
              display: inline-block;
              margin-left: 20px;
              vertical-align: top;
              margin-bottom: 10px;
            ">
            <span>客户名称：</span>
            <div style="width: 180px; height: 30px; border: 1px solid #ccc; line-height: 30px">
              {{ listOb.clientName }}</div>
          </div>
          <div style="
              display: inline-block;
              margin-left: 20px;
              vertical-align: top;
              margin-bottom: 10px;
            ">
            <span>供应商：</span>
            <div style="width: 180px; height: 30px; border: 1px solid #ccc; line-height: 30px">
              {{ listOb.supplierName }}</div>
          </div>
          <div style="
              display: inline-block;
              margin-left: 20px;
              vertical-align: top;
              margin-bottom: 10px;
            ">
            <span>单位：</span>
            <div style="width: 180px; height: 30px; border: 1px solid #ccc; line-height: 30px">
              {{ listOb.unit }}</div>
          </div>
          <div style="
              display: inline-block;
              margin-left: 20px;
              vertical-align: top;
              margin-bottom: 10px;
            ">
            <span>抽磅日期：</span>
            <div style="width: 180px; height: 30px; border: 1px solid #ccc; line-height: 30px">
              {{ listOb.billingDate }}</div>
          </div>
          <div style="
              display: inline-block;
              margin-left: 20px;
              vertical-align: top;
              margin-bottom: 10px;
            ">
            <span style="display: block">订单号：</span>
            <input style="border: 1.5px solid black; display: inline-block; padding: 5px; width: 180px" type="text"
              value="" />
          </div>
          <div style="
              display: inline-block;
              margin-left: 20px;
              vertical-align: top;
              margin-bottom: 10px;
            ">
            <span>原料名称：</span>
            <div style="width: 180px; height: 30px; border: 1px solid #ccc; line-height: 30px">
              {{ listOb.rawName }}</div>
          </div>
          <div style="
              display: inline-block;
              margin-left: 20px;
              vertical-align: top;
              margin-bottom: 10px;
            ">
            <span>纱牌：</span>
            <div style="width: 180px; height: 30px; border: 1px solid #ccc; line-height: 30px">
              {{ listOb.yarnCard }}</div>
          </div>
          <div style="
              display: inline-block;
              margin-left: 20px;
              vertical-align: top;
              margin-bottom: 10px;
            ">
            <span>纱批：</span>
            <div style="width: 180px; height: 30px; border: 1px solid #ccc; line-height: 30px">
              {{ listOb.batch }}</div>
          </div>
          <div style="
              display: inline-block;
              margin-left: 20px;
              vertical-align: top;
              margin-bottom: 10px;
            ">
            <span>色号：</span>
            <div style="width: 180px; height: 30px; border: 1px solid #ccc; line-height: 30px">
              {{ listOb.colourNumber }}</div>
          </div>
          <div style="
              display: inline-block;
              margin-left: 20px;
              vertical-align: top;
              margin-bottom: 10px;
            ">
            <span>色称：</span>
            <div style="width: 180px; height: 30px; border: 1px solid #ccc; line-height: 30px">
              {{ listOb.colorName }}</div>
          </div>
        </div>
        <table id="Table" style="margin: 10px auto;border-collapse:collapse">
          <thead>
            <tr>
              <th rowspan="2" style="border-right: 1px solid #dde2eb">纱球个数</th>
              <th colspan="2" style="border-right: 1px solid #dde2eb">来重</th>
              <th colspan="2" style="border-right: 1px solid #dde2eb">毛重</th>
              <th colspan="2" style="border-right: 1px solid #dde2eb">皮重</th>
              <th colspan="2" style="border-right: 1px solid #dde2eb">净重</th>
              <th colspan="2" style="border-right: 1px solid #dde2eb">盈亏重量</th>
              <th rowspan="2" style="border-right: 1px solid #dde2eb">备注</th>
            </tr>
            <tr>
              <th>公斤</th>
              <th>磅</th>
              <th>公斤</th>
              <th>磅</th>
              <th>公斤</th>
              <th>磅</th>
              <th>公斤</th>
              <th>磅</th>
              <th>公斤</th>
              <th>磅</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item, index) in listOb.list" :key="index">
              <td>{{ item['yarnBallNum'] }}</td>
              <td>{{ item['toHeavyKg'] }}</td>
              <td>{{ item['toHeavyPound'] }}</td>
              <td>{{ item['roughKg'] }}</td>
              <td>{{ item['roughPound'] }}</td>
              <td>{{ item['tareKg'] }}</td>
              <td>{{ item['tarePound'] }}</td>
              <td>{{ item['suttleKg'] }}</td>
              <td>{{ item['suttlePound'] }}</td>
              <td>{{ item['profitKg'] }}</td>
              <td>{{ item['profitPound'] }}</td>
              <td>{{ item['eachRemark'] }}</td>
            </tr>
          </tbody>
        </table>
        <div>
          <div style="
              display: inline-block;
              margin-left: 20px;
              vertical-align: top;
              margin-bottom: 10px;
            ">
            <span>来纱重量(KG)：</span>
            <div style="width: 180px; height: 30px; border: 1px solid #ccc; line-height: 30px">
              {{ pageData.yarnWeight }}</div>
          </div>
          <div style="
              display: inline-block;
              margin-left: 20px;
              vertical-align: top;
              margin-bottom: 10px;
            ">
            <span>每件重量(KG)：</span>
            <div style="width: 180px; height: 30px; border: 1px solid #ccc; line-height: 30px">
              {{ pageData.pieceWeight }}</div>
          </div>
          <div style="
              display: inline-block;
              margin-left: 20px;
              vertical-align: top;
              margin-bottom: 10px;
            ">
            <span>来纱件数：</span>
            <div style="width: 180px; height: 30px; border: 1px solid #ccc; line-height: 30px">
              {{ pageData.yarnNumber }}</div>
          </div>
          <div style="
              display: inline-block;
              margin-left: 20px;
              vertical-align: top;
              margin-bottom: 10px;
            ">
            <span>总欠重(KG)：</span>
            <div style="width: 180px; height: 30px; border: 1px solid #ccc; line-height: 30px">
              {{ pageData.deficitTotal }}</div>
          </div>
        </div>
      </div>
      <template #footer>
        <a-button type="primary" @click="handleBeforeOk">打印</a-button>
      </template>
    </a-modal>
  </pageTabelLayout>
</template>

<script lang="ts">
import { post } from '@/api/http'
import { useTable, useRowKey, useTableColumn, usePagination, useRowSelection } from '@/hooks/table'

import { ref, reactive, onMounted, onActivated, onUnmounted } from 'vue'
import Toolbar from '@/components/Toolbar.vue'
import { Form, Message, Modal } from '@arco-design/web-vue'
import { FormInstance } from '@arco-design/web-vue/es/form'
import emitter from '@/hooks/useEventBus'
import validate from '@/hooks/useValidate'
import { DatasetComponent } from 'echarts/components'
import { baseURL } from '../../../api/axios.config'
import axios from 'axios'
import dayjs from 'dayjs'
import usePermission from '@/store/modules/permission'
import filedownload from 'js-file-download'
import printJS from 'print-js'

import WHService, { Warhouse, CompanyList, WhTypeField } from '@/service/wh'
import { localeText } from '@/api/aggridZw'
import { pagingList } from '@/api/paging'
import { saveOrUpdateGridState as saveOrUpdateGridState01 } from '@/hooks/useGridState'
import { slicing } from '@/utils/caseFrimAndSecRig'
interface DefectName {
  id: any
  warehouseSerial: string | undefined
  warehouseName: string | undefined
  recordCode: any
  billingDate: string | undefined
  bookkeeper: string | undefined
  sourceOdd: string | undefined
  supplierCode: string | undefined
  supplierName: string | undefined
  rawCode: string | undefined
  rawName: string | undefined
  yarnCard: string | undefined
  colourNumber: string | undefined
  colorName: string | undefined
  batch: string | undefined
  loadExplain: string | undefined
  unit: string | undefined
  clientName: string | undefined
  smokePoundsRemark: string | undefined
  deleteState: number | undefined
  createName: string | undefined
  createTime: string | undefined
  updateName: string | undefined
  updateTime: string | undefined
  list: any[]
  whTypeName: string
  firm: string
  warehouseId: string
  stats: any
  warehouseCode: any
  orderNoField: any
  nameList: []
  rawMaterialCode: any
  rawMaterialName: any
  whs: any
  nameList1: any
  nameList2: any
  objInput: any
  customName: any
  companyId: any
  company: any
}
export default {
  name: 'RawMaterialWeighingRecord',
  setup() {
    const headerShow = ref<boolean>(true)
    //查询
    const scrollbar = ref(true)
    const { selectedRowKeys, onSelectionChange } = useRowSelection()
    const selectedRowKeysCf = useRowSelection()
    const pagination = usePagination(doRefresh)
    const table = useTable()
    const rowKey = useRowKey('id')
    //检验表单是否含有中文的方法
    const hasChiese = validate.includeChinese
    var tableColumns = useTableColumn([
      {
        title: '公司',
        key: 'company',
        dataIndex: 'company',
        width: 150,
      },
      {
        title: '开单日期',
        key: 'billingDate',
        dataIndex: 'billingDate',
        width: 150,
      },
      {
        title: '仓库编号',
        key: 'warehouseSerial',
        dataIndex: 'warehouseSerial',
        width: 150,
      },
      {
        title: '仓库名称',
        key: 'warehouseName',
        dataIndex: 'warehouseName',
        width: 150,
      },

      // {
      //     title: "供应商编号",
      //     key: "supplierCode",
      //     dataIndex: "supplierCode",
      //     width: 150
      // },
      {
        title: '供应商名称',
        key: 'supplierName',
        dataIndex: 'supplierName',
        width: 150,
      },
      {
        title: '原料编号',
        key: 'rawCode',
        dataIndex: 'rawCode',
        width: 150,
      },
      {
        title: '原料名称',
        key: 'rawName',
        dataIndex: 'rawName',
        width: 150,
      },
      {
        title: '客户名称',
        key: 'clientName',
        dataIndex: 'clientName',
        width: 150,
      },
      {
        title: '纱牌',
        key: 'yarnCard',
        dataIndex: 'yarnCard',
        width: 150,
      },
      {
        title: '纱批',
        key: 'batch',
        dataIndex: 'batch',
        width: 150,
      },
      {
        title: '等级',
        key: 'level',
        dataIndex: 'level',
        width: 150,
      },
      {
        title: '色号',
        key: 'colourNumber',
        dataIndex: 'colourNumber',
        width: 150,
      },
      {
        title: '色称',
        key: 'colorName',
        dataIndex: 'colorName',
        width: 150,
      },
      // {
      //   title: '来重',
      //   key: '',
      //   children: [
      //     { title: '公斤', dataIndex: 'toHeavyKg', width: 150 },
      //     { title: '磅', dataIndex: 'toHeavyPound', width: 150 },
      //   ],
      // },
      // {
      //   title: '毛重',
      //   key: '',
      //   children: [
      //     { title: '公斤', dataIndex: 'roughKg', width: 150 },
      //     { title: '磅', dataIndex: 'roughPound', width: 150 },
      //   ],
      // },
      // {
      //   title: '皮重',
      //   key: '',
      //   children: [
      //     { title: '公斤', dataIndex: 'tareKg', width: 150 },
      //     { title: '磅', dataIndex: 'tarePound', width: 150 },
      //   ],
      // },
      // {
      //   title: '净重',
      //   key: '',
      //   children: [
      //     { title: '公斤', dataIndex: 'suttleKg', width: 150 },
      //     { title: '磅', dataIndex: 'suttlePound', width: 150 },
      //   ],
      // },
      // {
      //   title: '盈亏重量',
      //   key: '',
      //   children: [
      //     { title: '公斤', dataIndex: 'profitKg', width: 150 },
      //     { title: '磅', dataIndex: 'profitPound', width: 150 },
      //   ],
      // },

      {
        title: '备注',
        key: 'eachRemark',
        dataIndex: 'eachRemark',
        width: 150,
      },

      {
        title: '记录单号',
        key: 'recordCode',
        dataIndex: 'recordCode',
        width: 150,
      },
      {
        title: '修改人',
        key: 'updateName',
        dataIndex: 'updateName',
        width: 150,
      },
      {
        title: '入库单号',
        key: 'sourceOdd',
        dataIndex: 'sourceOdd',
        width: 150,
      },
      {
        title: '载量说明',
        key: 'loadExplain',
        dataIndex: 'loadExplain',
        width: 150,
      },

      {
        title: '创建人',
        key: 'createName',
        dataIndex: 'createName',
        width: 150,
      },
      {
        title: '创建时间',
        key: 'createTime',
        dataIndex: 'createTime',
        width: 180,
      },
      {
        title: '最后修改人',
        key: 'updateName',
        dataIndex: 'updateName',
        width: 150,
      },
      {
        title: '最后修改时间',
        key: 'updateTime',
        dataIndex: 'updateTime',
        width: 180,
      },
      {
        title: '操作',
        key: 'id',
        dataIndex: 'id',
        slotName: 'action',
        width: 150,
        fixed: 'right',
      },
    ])

    //成分信息表格
    const tableColumnsCf = useTableColumn([
      {
        title: '纱球个数',
        key: 'yarnBallNum',
        dataIndex: 'yarnBallNum',
        width: 150,
        slotName: 'yarnBallNum',
      },
      {
        title: '来重',
        key: '',
        children: [
          { title: '公斤', dataIndex: 'toHeavyKg', width: 150, slotName: 'toHeavyKg' },
          { title: '磅', dataIndex: 'toHeavyPound', width: 150, slotName: 'toHeavyPound' },
        ],
      },
      {
        title: '毛重',
        key: '',
        children: [
          { title: '公斤', dataIndex: 'roughKg', width: 150, slotName: 'roughKg' },
          { title: '磅', dataIndex: 'roughPound', width: 150, slotName: 'roughPound' },
        ],
      },
      {
        title: '皮重',
        key: '',
        children: [
          { title: '公斤', dataIndex: 'tareKg', width: 150, slotName: 'tareKg' },
          { title: '磅', dataIndex: 'tarePound', width: 150, slotName: 'tarePound' },
        ],
      },
      {
        title: '净重',
        key: '',
        children: [
          { title: '公斤', dataIndex: 'suttleKg', width: 150, slotName: 'suttleKg' },
          { title: '磅', dataIndex: 'suttlePound', width: 150, slotName: 'suttlePound' },
        ],
      },
      {
        title: '盈亏重量',
        key: '',
        children: [
          { title: '公斤', dataIndex: 'profitKg', width: 150, slotName: 'profitKg' },
          { title: '磅', dataIndex: 'profitPound', width: 150, slotName: 'profitPound' },
        ],
      },

    ])

    let tc: any[] = tableColumns.map((o) => {
      let obj = {
        headerName: o.title,
        field: o.key,
        pinned: o['fixed'],
      }
      if (o.slotName === 'action') {
        obj['resizable'] = false
        obj['filter'] = false
        obj['sortable'] = false
        obj['lockPosition'] = 'right'
        obj['width'] = 80
        obj['cellRenderer'] = {
          template: `<el-button style="color:#165dff;"   v-if="isEdit" link @click="a">修改</el-button>`,
          setup(props: any) {
            const isEdit = ref(pageData.isEdit)
            const a = () => {
              editHandler(props.params.data)
            }
            return {
              a,
              isEdit,
            }
          },
        }
      }

      return obj
    })

    let a = [
      {
        showRowGroup: 'hide_def',
        headerName: '',
        checkboxSelection: true,
        headerCheckboxSelection: true,
        pinned: 'left',
        width: 50,
        resizable: false,
        filter: false,
        sortable: false,
        minWidth: 50,
        maxWidth: 50,
        lockPosition: 'left',
      },
    ]
    tc = a.concat(tc)

    const scroll = {
      x: 2000,
      y: 200,
    }
    const tablediv = ref(null)
    const pageData = reactive<{
      DefectName: DefectName[]
      showAdd: boolean
      sideTitle: string
      pageLoading: boolean
      height: number
      tablediv: any
      rHeight: number | undefined
      DefectNameList: []
      DefectNameList1: []
      rHeight1: number | undefined
      recordCode: string | undefined
      billingDate: any
      rawCode: string | undefined
      rawName: string | undefined
      yarnCard: string | undefined
      colourNumber: string | undefined
      colorName: string | undefined
      batch: string | undefined
      supplierCode: string | undefined
      supplierName: string | undefined
      btnList: any[]
      isEdit: boolean
      dateStart: any
      dateEnd: any
      list: any[]
      yarnWeight: string | undefined
      pieceWeight: string | undefined
      yarnNumber: string | undefined
      deficitTotal: string | undefined
      unitList: []
      sourceOddList: any[]
      corporateList: any[]
      corporateId: string
      corporateLoading: boolean
      pieceWeight1: any
    }>({
      DefectName: [],
      showAdd: false,
      sideTitle: '新增原料抽磅记录',
      pageLoading: false,
      height: 0,
      tablediv: null,
      rHeight: 0,
      DefectNameList: [],
      rHeight1: 0,
      recordCode: '',
      billingDate: '',
      rawCode: '',
      rawName: '',
      yarnCard: '',
      colourNumber: '',
      colorName: '',
      batch: '',
      supplierCode: '',
      supplierName: '',
      DefectNameList1: [],
      btnList: [],
      isEdit: false,
      dateStart: '',
      dateEnd: '',
      list: [],
      yarnWeight: '',
      pieceWeight: '',
      yarnNumber: '',
      deficitTotal: '',
      unitList: [],
      sourceOddList: [],
      corporateList: [],
      corporateId: '',
      corporateLoading: false,
      pieceWeight1: 0,
    })
    let allDataList: any[] = []
    const total = ref(0)
    const page = ref(1)
    const size = ref(10)
    function PageSize(val: any) {
      pagination.page = val
      doRefresh()
    }
    const corporateRef = ref<any>()
    //公司change事件
    const corporateChange = (event: any) => {
      nextTick(() => {
        dataForm.company = slicing(corporateRef.value.selectViewValue[0].label)
        whList.value = []
        dataForm.warehouseId = ''
        whService.getWarhouseList(event, '原纱仓')
      })
    }
    // 获取公司列表
    const getCorporateList = async () => {
      try {
        pageData.corporateLoading = true
        const res = await post({ url: 'org/baCompany/getTreeCompanyByUser' })
        if (res.code == 200) {
          pageData.corporateList = res.data
          return
        }
        Message.error(res.message)
      } catch (error: any) {
        pageData.corporateLoading = false
      } finally {
        pageData.corporateLoading = false
      }
    }
    function change1(val: any) {
      pagination.pageSize = val
      doRefresh()
    }

    function doRefresh() {
      pageData.pageLoading = true
      updateGridState01()
      post({
        url: 'qms/stockSmokePounds/selectPage',
        data: {
          page: pagination.page,
          size: pagination.pageSize,
          deleteState: 0,
          recordCode: pageData.recordCode,
          // billingDate: [pageData.dateStart, pageData.dateEnd],
          beginDate: pageData.dateStart,
          endDate: pageData.dateEnd,
          rawCode: pageData.rawCode,
          rawName: pageData.rawName,
          yarnCard: pageData.yarnCard,
          colourNumber: pageData.colourNumber,
          colorName: pageData.colorName,
          batch: pageData.batch,
          supplierCode: pageData.supplierCode,
          supplierName: pageData.supplierName,
        },
      })
        .then(({ data, code }: any) => {
          if (code === 200) {
            table.handleSuccess(data.list)
            // pagination.setTotalSize(data.total);
            gridOption.value.setRowData(data.list)
            total.value = data.total
            allDataList = data.list
          }
        })
        .catch(console.log)
        .finally(() => {
          pageData.pageLoading = false
        })
    }

    //模糊查询
    //下拉框得到焦点 原料编码
    const focusSel = () => {
      selCxAll({ rawCode: '' })
    }
    //下拉数据  原料编码
    const options = ref<any>(pageData.DefectNameList)
    const loading = ref(false)
    const handleSearch = (value: any) => {
      if (value) {
        const ob = { rawCode: value }
        loading.value = true
        selCxAll(ob)
        cxRawName(ob)
        options.value = pageData.DefectNameList
        loading.value = false
      } else {
        options.value = []
      }
    }
    //下拉框查询 原料编码
    function selCxAll(val: any) {
      post({
        url: 'qms/stockSmokePounds/getFieldValue',
        data: val,
      }).then(({ data, code }: any) => {
        if (code === 200) {
          // (data as string[]).splice(0, 0, "全部");
          pageData.DefectNameList = data
        } else {
          Message.error({
            content: '查询失败！',
            duration: 5000,
          })
        }
      })
    }
    //查询 原料名称
    function cxRawName(val: any) {
      post({
        url: 'qms/stockSmokePounds/select',
        data: val,
      }).then(({ data, code }: any) => {
        if (code === 200) {
          // (data as string[]).splice(0, 0, "全部");
          pageData.rawName = data[0]['rawName']
        } else {
          Message.error({
            content: '查询失败！',
            duration: 5000,
          })
        }
      })
    }

    //模糊查询
    //下拉框得到焦点 供应商编号
    const focusSel1 = () => {
      selCxAll1({ supplierCode: '' })
    }
    //下拉数据  供应商编号
    const options1 = ref<any>(pageData.DefectNameList1)
    const loading1 = ref(false)
    const handleSearch1 = (value: any) => {
      if (value) {
        const ob = { supplierCode: value }
        loading.value = true
        selCxAll1(ob)

        options1.value = pageData.DefectNameList1
        loading1.value = false
      } else {
        options1.value = []
      }
    }
    //下拉框查询 供应商编号
    function selCxAll1(val: any) {
      post({
        url: 'qms/stockSmokePounds/getFieldValue',
        data: val,
      }).then(({ data, code }: any) => {
        if (code === 200) {
          // (data as string[]).splice(0, 0, "全部");
          pageData.DefectNameList1 = data
        } else {
          Message.error({
            content: '查询失败！',
            duration: 5000,
          })
        }
      })
    }
    const changeCose = () => {
      cxSupplierName({ supplierCode: pageData.supplierCode })
    }
    //查询 供应商名称
    function cxSupplierName(val: any) {
      pageData.supplierName = ''
      if (val.supplierCode == undefined || val.supplierCode == '') {
        return
      }
      post({
        url: 'qms/stockSmokePounds/select',
        data: val,
      }).then(({ data, code }: any) => {
        if (code === 200) {
          // (data as string[]).splice(0, 0, "全部");

          pageData.supplierName = data[0]['supplierName']
        } else {
          Message.error({
            content: '查询失败！',
            duration: 5000,
          })
        }
      })
    }
    onMounted(() => {
      getCorporateList()
      emitter.on('refresh-RawMaterialWeighingRecord', () => {
        pageData.rHeight1 = document.getElementById('IncomingInspection')?.clientHeight
        //表格的高
        if (pageData.rHeight1 !== undefined) {
          pageData.rHeight1 = pageData.rHeight1 - 300
        }
      })
      pageData.rHeight = document.getElementsByClassName('main-section')[0]?.clientHeight

      //弹出层的高
      if (pageData.rHeight !== undefined) {
        pageData.rHeight = pageData.rHeight - 100
      }

      pageData.rHeight1 = document.getElementById('IncomingInspection')?.clientHeight
      //表格的高
      if (pageData.rHeight1 !== undefined) {
        pageData.rHeight1 = pageData.rHeight1 - 300
      }

      window.addEventListener('resize', () => {
        pageData.rHeight1 = document.getElementById('IncomingInspection')?.clientHeight
        //表格的高
        if (pageData.rHeight1 !== undefined) {
          pageData.rHeight1 = pageData.rHeight1 - 300
        }

        pageData.rHeight = document.getElementsByClassName('main-section')[0]?.clientHeight
        //弹出层的高
        if (pageData.rHeight !== undefined) {
          pageData.rHeight = pageData.rHeight - 100
        }
      })
      doRefresh()
    })

    //查询
    const selectHandler = () => {
      pagination.page = 1
      doRefresh()
    }

    const addHandler = () => {
      for (var key in dataForm) {
        if (key === 'id') {
          dataForm[key] = null
        } else if (key === 'deleteState' || key === 'donationMoney' || key === 'deleteDonation') {
          dataForm[key] = 0
        } else if (key == 'list') {
          dataForm[key] = []
        } else {
          dataForm[key] = ''
        }
      }
      post({
        url: '/qms/stockSmokePounds/getCodeGenerate',
        // data: obData,
      })
        .then(({ code, data }: any) => {
          if (code === 200) {
            dataForm.recordCode = data
            // console.log(dataForm.recordCode, 'rrrrrrrrrrrrrrrrrrrrrrr');
          }
        })
        .finally(() => {
          pageData.pageLoading = false
        })
      listOb.list = []
      for (let i = 0; i < 10; i++) {
        listOb.list.push({
          id: 'add' + i,
          yarnBallNum: 0,
          toHeavyKg: pageData.pieceWeight1,
          toHeavyPound: parseFloat((pageData.pieceWeight1 * 2.20462262185).toFixed(2)),
          roughKg: 0,
          roughPound: 0,
          tareKg: 0,
          tarePound: 0,
          suttleKg: 0,
          suttlePound: 0,
          profitKg: 0,
          profitPound: 0,
          eachRemark: '',
          add: true,
        })
      }
      pageData.showAdd = true
      pageData.sideTitle = '新增原料抽磅记录'
    }
    const dataForm: any = reactive({
      id: null,
      warehouseSerial: '',
      warehouseName: '',
      recordCode: '',
      billingDate: '',
      bookkeeper: '',
      sourceOdd: '',
      supplierCode: '',
      supplierName: '',
      rawCode: '',
      rawName: '',
      yarnCard: '',
      colourNumber: '',
      colorName: '',
      batch: '',
      loadExplain: '',
      unit: '',
      clientName: '',
      smokePoundsRemark: '',
      deleteState: 0,
      createName: '',
      createTime: '',
      updateName: '',
      updateTime: '',
      list: [],
      nameList1: [],
      nameList: [],
      firm: '',
      whTypeName: '',
      warehouseId: '',
      stats: '',
      warehouseCode: '',
      orderNoField: '',
      rawMaterialCode: '',
      rawMaterialName: '',
      whs: '',
      nameList2: [],
      objInput: '',
      customName: '',
      companyId: '',
      company: '',
      level: ''
    })

    // 表格准备事件
    const gridOption = ref()
    const colState = ref()
    const gridReady = (params: any) => {
      gridOption.value = params.api
      colState.value = params.columnApi
    }
    const formRef = ref<FormInstance>()
    const sideOk = () => {
      formRef.value?.validate().then((err) => {
        if (!err) {
          listOb.list.forEach(function (o: any) {
            if ((o['id'] + '').indexOf('add') != -1) {
              o['id'] = null
            }
          })
          let listOP = whList.value.filter(function (o: any) {
            return o['id'] == dataForm.warehouseId
          })
          dataForm.warehouseName = listOP[0]['warehouseName']
          dataForm.warehouseSerial = listOP[0]['warehouseCode']
          let obData = {}
          obData['data'] = dataForm
          // obData["list"] = listOb.list
          obData['stockSmokePoundsSon'] = listOb.list

          // dataForm["list"]=listOb.list
          if (pageData.sideTitle === '新增原料抽磅记录') {
            pageData.pageLoading = true
            post({
              url: 'qms/stockSmokePounds/insert',
              data: obData,
              // data: {
              //     dataForm,
              //     stockSmokePoundsSon: listOb.list,
              // }
            })
              .then((res: any) => {
                if (res.code === 200) {
                  formRef.value?.resetFields()

                  pageData.showAdd = false

                  Message.success({
                    content: '新增成功',
                    duration: 5000,
                  })
                  doRefresh()
                } else {
                  Message.error({
                    content: res.message,
                    duration: 5000,
                  })
                }
              })
              .finally(() => {
                pageData.pageLoading = false
              })
          } else {
            pageData.pageLoading = true
            post({
              url: 'qms/stockSmokePounds/update',
              data: obData,
            })
              .then((res: any) => {
                if (res.code === 200) {
                  formRef.value?.resetFields()
                  pageData.showAdd = false

                  Message.success({
                    content: '修改成功',
                    duration: 5000,
                  })
                  doRefresh()
                } else {
                  Message.error({
                    content: res.message,
                    duration: 5000,
                  })
                }
              })
              .finally(() => {
                pageData.pageLoading = false
              })
          }
        }
      })
    }
    const deleteHandler = () => {
      // if (selectedRowKeys.value.length === 0) {
      //     return;
      // }
      if (gridOption.value.getSelectedRows() === 0) {
        return
      }
      pageData.pageLoading = true
      Modal.confirm({
        title: '系统提示',
        content: '确认删除选中的数据?',
        onOk() {
          post({
            url: 'qms/stockSmokePounds/delete',
            // data: selectedRowKeys.value,
            data: gridOption.value.getSelectedRows().map((o: any) => {
              return o.id
            }),
          })
            .then(({ code, data }: any) => {
              if (code === 200) {
                Message.success({
                  content: '删除成功',
                  duration: 5000,
                })
                pagination.page = 1
                doRefresh()
              } else {
                Message.error({
                  content: '修改失败',
                  duration: 5000,
                })
              }
            })
            .finally(() => {
              pageData.pageLoading = false
            })
        },
      })
    }
    let idToData: any[] = []
    const editHandler = (record: DefectName) => {
      whService.getWarhouseList(record.companyId, '原纱仓')
      for (var key in record) {
        dataForm[key] = record[key]
      }
      pageData.sideTitle = '修改原料抽磅记录'
      pageData.showAdd = true

      idToData = allDataList.filter((item) => item.id == record.id)
      if (idToData.length > 0) {
        for (let key in idToData[0]) {
          dataForm[key] = idToData[0][key]
        }

        listOb['list'] = idToData[0]['list']
      }
    }
    //判断是否填写了中文
    const isChiese = (value: string, cb: Function) => {
      return new Promise<void>((resolve) => {
        if (window.encodeURI(value).indexOf('%') !== -1) {
          cb('填写的值只能是英文数字组合或英文，数字！')
        }
        resolve()
      })
    }
    //input离开焦点 将小写转大写
    const inputBlur = () => {
      dataForm.recordCode = dataForm.recordCode.toUpperCase()
    }
    //导出
    const exports = () => {
      // if (selectedRowKeys.value.length === 0) {
      //     Message.error('请先勾选')
      //     return
      // }
      if (gridOption.value.getSelectedRows() === 0) {
        Message.error('请先勾选')
        return
      } else {
        //将表头拼接出来
        let head =
          "<th rowspan='2'>开单日期</th><th rowspan='2'>仓库编号</th><th rowspan='2'>仓库名称</th><th rowspan='2'>供应商名称</th><th rowspan='2'>原料编号</th><th rowspan='2'>原料名称</th><th rowspan='2'>客户名称</th><th rowspan='2'>纱牌</th><th rowspan='2'>纱批</th><th rowspan='2'>色号</th><th rowspan='2'>色称</th>"
        head +=
          "<th colspan='2'>来重</th><th colspan='2'>毛重</th><th colspan='2'>皮重</th><th colspan='2'>净重</th><th colspan='2'>盈亏重量</th><th rowspan='2'>记录单号</th><th rowspan='2'>修改人</th>"
        head +=
          "<th rowspan='2'>入库单号</th><th rowspan='2'>载量说明</th><th rowspan='2'>创建人</th><th rowspan='2'>创建时间</th><th rowspan='2'>最后修改人</th><th rowspan='2'>最后修改时间</th>"
        let head1 =
          '<th>公斤</th><th>磅</th><th>公斤</th><th>磅</th><th>公斤</th><th>磅</th><th>公斤</th><th>磅</th><th>公斤</th><th>磅</th>'
        // //拿到当前表格数据与勾选的行做筛选
        // let idList = gridOption.value.getSelectedRows().map(function (o: any) {
        //   return o['id']
        // })

        // let nowRow = table.dataList.filter(function (o) {
        //   return idList.includes(o['id'])
        // })
        let nowRow: any = []
        gridOption.value.getSelectedRows().forEach(function (o: any) {
          o['list'].forEach(function (o1: any) {
            for (let key in o) {
              o1[key] = o[key]
            }
            nowRow.push(o1)
          })
        })


        let body = ''
        nowRow.forEach(function (o: any) {
          body += '<tr><td>' + o['billingDate'] + '</td>'
          body += '<td>' + o['warehouseSerial'] + '</td>'
          body += '<td>' + o['warehouseName'] + '</td>'
          body += '<td>' + o['supplierName'] + '</td>'
          body += '<td>' + o['rawCode'] + '</td>'
          body += '<td>' + o['rawName'] + '</td>'
          body += '<td>' + o['clientName'] + '</td>'
          body += '<td>' + o['yarnCard'] + '</td>'
          body += '<td>' + o['batch'] + '</td>'
          body += '<td>' + o['colourNumber'] + '</td>'
          body += '<td>' + o['colorName'] + '</td>'
          body += '<td>' + (o['toHeavyKg'] == undefined ? "" : o['toHeavyKg']) + '</td>'
          body += '<td>' + (o['toHeavyPound'] == undefined ? "" : o['toHeavyPound']) + '</td>'
          body += '<td>' + (o['roughKg'] == undefined ? "" : o['roughKg']) + '</td>'
          body += '<td>' + (o['roughPound'] == undefined ? "" : o['roughPound']) + '</td>'
          body += '<td>' + (o['tareKg'] == undefined ? "" : o['tareKg']) + '</td>'
          body += '<td>' + (o['tarePound'] == undefined ? "" : o['tarePound']) + '</td>'
          body += '<td>' + (o['suttleKg'] == undefined ? "" : o['suttleKg']) + '</td>'
          body += '<td>' + (o['suttlePound'] == undefined ? "" : o['suttlePound']) + '</td>'
          body += '<td>' + (o['profitKg'] == undefined ? "" : o['profitKg']) + '</td>'
          body += '<td>' + (o['profitPound'] == undefined ? "" : o['profitPound']) + '</td>'
          body += '<td>' + o['recordCode'] + '</td>'
          body += '<td>' + o['updateName'] + '</td>'
          body += '<td>' + o['sourceOdd'] + '</td>'
          body += '<td>' + o['loadExplain'] + '</td>'
          body += '<td>' + o['createName'] + '</td>'
          body += '<td>' + o['createTime'] + '</td>'
          body += '<td>' + o['updateName'] + '</td>'
          body += '<td>' + o['updateTime'] + '</td>'
          body += '</tr>'
        })
        tableToXlsx(head, '原料抽磅记录', body, head1)
      }
    }

    function tableToXlsx(head: any, filename: any, body: any, head1: any) {
      const uri = 'data:application/vnd.ms-excel;base64,',
        template = `<html>
            <head><meta charset="UTF-8"></head>
            <body><table border="1"><tr>${head}</tr><tr>${head1}</tr>${body}</table></body>
        </html>`

      const a = document.createElement('a')
      a.href = uri + window.btoa(unescape(encodeURIComponent(template)))
      a.download = filename
      a.click()
      document.removeChild(a)
    }

    //成分添加一行 点击新增按钮
    const addLine = () => {
      let addNum = 10
      if (pageData.sideTitle === '新增原料抽磅记录') {
        listOb.list.push({
          id: 'add' + addNum++,
          yarnBallNum: 0,
          toHeavyKg: pageData.pieceWeight1,
          toHeavyPound: parseFloat((pageData.pieceWeight1 * 2.20462262185).toFixed(2)),
          roughKg: 0,
          roughPound: 0,
          tareKg: 0,
          tarePound: 0,
          suttleKg: 0,
          suttlePound: 0,
          profitKg: 0,
          profitPound: 0,
          eachRemark: '',
          add: true,
        })
      } else if (pageData.sideTitle === '修改原料抽磅记录') {
        //判断是否有这个key
        if (idToData[0].hasOwnProperty('list')) {
          listOb['list'] = idToData[0]['list']
          //在这个数组前面添加一行
          listOb.list.unshift({
            id: 'add' + addNum++,
            yarnBallNum: 0,
            toHeavyKg: pageData.pieceWeight1,
            toHeavyPound: parseFloat((pageData.pieceWeight1 * 2.20462262185).toFixed(2)),
            roughKg: 0,
            roughPound: 0,
            tareKg: 0,
            tarePound: 0,
            suttleKg: 0,
            suttlePound: 0,
            profitKg: 0,
            profitPound: 0,
            eachRemark: '',

            add: true,
          })
        } else {
          listOb['list'] = []
          listOb['list'].push({
            id: 'add' + addNum++,
            yarnBallNum: 0,
            toHeavyKg: pageData.pieceWeight1,
            toHeavyPound: 0,
            roughKg: 0,
            roughPound: 0,
            tareKg: 0,
            tarePound: 0,
            suttleKg: 0,
            suttlePound: 0,
            profitKg: 0,
            profitPound: 0,
            eachRemark: '',
            add: true,
          })
        }
      }
    }
    //成分 删除
    const delLine = () => {
      if (selectedRowKeysCf.selectedRowKeys.value.length === 0) {
        Message.error({
          content: '请先勾选',
          duration: 5000,
        })
        return
      }
      listOb['list'] = listOb['list'].filter(function (o: any) {
        return selectedRowKeysCf.selectedRowKeys.value.indexOf(o['id']) === -1
      })
      selectedRowKeysCf.selectedRowKeys.value.length = 0
    }

    //打印弹出框
    const visible = ref(false)

    const listOb = reactive<any>({
      id: null,
      clientName: '',
      supplierName: '',
      unit: '',
      billingDate: '',
      ddCode: '',
      rawName: '',
      yarnCard: '',
      batch: '',
      colourNumber: '',
      colorName: '',
      list: [],
    })
    const handleClick = () => {
      for (var key in listOb) {
        if (key != 'list') {
          listOb[key] = ''
        } else {
          listOb[key] = []
        }
      }

      if (gridOption.value.getSelectedRows().length <= 0) {
        Message.warning({
          content: '只能勾选一条数据，请重新勾选！',
          duration: 5000,
        })
      } else {

        printPdf(gridOption.value.getSelectedRows().map((o: any) => { return o['id'] }))
        // pageData.list = allDataList.filter((item) => item.id == gridOption.value.getSelectedRows()[0])
        // if (pageData.list.length > 0) {
        //   for (var key in pageData.list[0]) {
        //     listOb[key] = pageData.list[0][key]
        //   }

        //   let ob = {
        //     yarnBallNum: '平均值',
        //     toHeavyKg: 0,
        //     toHeavyPound: 0,
        //     roughKg: 0,
        //     roughPound: 0,
        //     tareKg: 0,
        //     tarePound: 0,
        //     suttleKg: 0,
        //     suttlePound: 0,
        //     profitKg: 0,
        //     profitPound: 0,
        //     eachRemark: '',
        //   }
        //   listOb['list'].forEach(function (o: any) {
        //     ob['toHeavyKg'] += o['toHeavyKg']
        //     ob['toHeavyPound'] += o['toHeavyPound']
        //     ob['roughKg'] += o['roughKg']
        //     ob['roughPound'] += o['roughPound']
        //     ob['tareKg'] += o['tareKg']
        //     ob['tarePound'] += o['tarePound']
        //     ob['suttleKg'] += o['suttleKg']
        //     ob['suttlePound'] += o['suttlePound']
        //     ob['profitKg'] += o['profitKg']
        //     ob['profitPound'] += o['profitPound']
        //   })
        //   listOb['list'].push(ob)
        // }
        // visible.value = true
      }
    }
    const handleBeforeOk = () => {
      printJS({
        printable: 'rawmat',
        type: 'html',
        targetStyles: ['*'],
      })
    }
    const handleCancel = () => {
      visible.value = false
    }

    const focusunit = () => {
      getUnitList('')
    }
    // 单位下拉框
    const searchUnit = (value: any) => {
      if (value) {
        loading.value = true
        getUnitList(value)
        options.value = pageData.unitList
        loading.value = false
      } else {
        options.value = []
      }
    }
    // 单位下拉框
    const getUnitList = (val: any) => {
      post({
        url: 'dict/dictTypeDetail/getListByMap',
        data: {
          codeType: 17,
          detailName: val,
        },
      }).then(({ code, data }: any) => {
        if (code == 200) {
          pageData.unitList = data
        } else {
          Message.error({
            content: '查询失败',
            duration: 5000,
          })
        }
      })
    }

    //设置权限
    // ['查询', '新增', '删除', '导出', '导入']
    const permissionStore = usePermission()

    if (permissionStore.hasPermisson('ylcbjl.cx')) {
      pageData.btnList.push('查询')
    }
    if (permissionStore.hasPermisson('ylcbjl.xz')) {
      pageData.btnList.push('新增')
    }
    if (permissionStore.hasPermisson('ylcbjl.sc')) {
      pageData.btnList.push('删除')
    }
    if (permissionStore.hasPermisson('ylcbjl.dy')) {
      pageData.btnList.push('打印')
    }
    if (permissionStore.hasPermisson('ylcbjl.dc')) {
      pageData.btnList.push('导出')
    }

    if (permissionStore.hasPermisson('ylcbjl.xg')) {
      pageData.isEdit = true
    }
    const defaultColDef = {
      sortable: true,
      resizable: true,
      filter: true,
      // flex: 1
    }
    //公斤改变过 磅自动计算
    const poundChange = (record: any, num: any) => {
      if (num == 1) {
        record.toHeavyPound = parseFloat((record.toHeavyKg * 2.20462262185).toFixed(2))
        record.profitKg = parseFloat(record.suttleKg) - parseFloat(record.toHeavyKg)
        record.profitKg = parseFloat(record.profitKg.toFixed(2))
      } else if (num == 2) {
        record.roughPound = parseFloat((record.roughKg * 2.20462262185).toFixed(2))
        record.suttleKg = parseFloat(record.roughKg) - parseFloat(record.tareKg)
        record.suttleKg = parseFloat(record.suttleKg.toFixed(2))
        record.suttlePound = parseFloat((record.suttleKg * 2.20462262185).toFixed(2))
        record.profitKg = parseFloat(record.suttleKg) - parseFloat(record.toHeavyKg)
        record.profitKg = parseFloat(record.profitKg.toFixed(2))
        record.profitPound = parseFloat((record.profitKg * 2.20462262185).toFixed(2))
      } else if (num == 3) {
        record.tarePound = parseFloat((record.tareKg * 2.20462262185).toFixed(2))
        record.suttleKg = parseFloat(record.roughKg) - parseFloat(record.tareKg)
        record.suttleKg = parseFloat(record.suttleKg.toFixed(2))
        record.suttlePound = parseFloat((record.suttleKg * 2.20462262185).toFixed(2))
        record.profitKg = parseFloat(record.suttleKg) - parseFloat(record.toHeavyKg)
        record.profitKg = parseFloat(record.profitKg.toFixed(2))
        record.profitPound = parseFloat((record.profitKg * 2.20462262185).toFixed(2))
      } else if (num == 4) {
      } else if (num == 5) {
      }
    }
    //模糊查询入库单号
    //模糊查询
    //下拉框得到焦点
    const focusSelSourceOdd = () => {
      selCxAllSourceOdd({ rawCode: '' })
    }
    //下拉数据
    const optionsSourceOdd = ref<any>(pageData.sourceOddList)

    const handleSearchSourceOdd = (value: any) => {
      if (value) {
        const ob = { rawCode: value }
        loading.value = true
        selCxAllSourceOdd(ob)
        optionsSourceOdd.value = pageData.sourceOddList
      } else {
        optionsSourceOdd.value = []
      }
    }
    //下拉框查询
    function selCxAllSourceOdd(val: any) {
      post({
        url: 'qms/stockSmokePounds/getFieldValue',
        data: val,
      }).then(({ data, code }: any) => {
        if (code === 200) {
          // (data as string[]).splice(0, 0, "全部");
          pageData.sourceOddList = data
          loading.value = false
        } else {
          Message.error({
            content: '查询失败！',
            duration: 5000,
          })
        }
      })
    }
    //入库单号发生改变调接口 查出所有数据
    const changeSourceOdd = (val: any) => { }

    const whList = ref<any[]>([])
    const companyListof = ref<any[]>([])
    const whService = new WHService()
    const whTypeList = whService.whTypeList
    const whTypeFieldList = whService.whTypeFieldList
    const companyList: any = whService.companyList
    const searchData = reactive<{
      whTypeName: string
      firm: string
      warehouseId: string
      stats: any
      warehouseCode: any
      orderNoField: any
      nameList: []
      rawMaterialCode: any
      rawMaterialName: any
      whs: any
      nameList1: any
      nameList2: any
      batch: any
      objInput: any
    }>({
      nameList1: [],
      nameList: [],
      firm: '',
      whTypeName: '',
      warehouseId: '',
      stats: '',
      warehouseCode: '',
      orderNoField: '',
      rawMaterialCode: '',
      rawMaterialName: '',
      whs: '',
      nameList2: [],
      batch: '',
      objInput: '',
    })
    // 公司下拉框 改变
    const companyChange = (val: any) => {
      whList.value = []
      dataForm.warehouseId = ''
      whService.getWarhouseList(val, '原纱仓')
    }
    watch(
      () => whService.whList.value,
      (o, n) => {
        whList.value = whService.whList.value
      }
    )

    // 入库单号 下拉框得到焦点
    const focusSel9 = () => {
      selCxAll9({ in_stock_number: '', warehouse_id: dataForm.warehouseId, queryFields: 'in_stock_number' })
    }

    const handleSearch9 = (value: any) => {
      if (value) {
        const ob = {
          in_stock_number: value,
          warehouse_id: dataForm.warehouseId,
          queryFields: 'in_stock_number',
        }
        loading.value = true
        selCxAll9(ob)
        options.value = dataForm.nameList
        loading.value = false
      } else {
        options.value = []
      }
    }
    const selCxAll9 = (val: any): void => {
      post({
        url: 'wms/yarnInStock/getInStockNumberList',
        data: val,
      }).then(({ code, data }) => {
        if (code === 200) {
          dataForm.nameList = data
        }
      })
    }

    // 原料编号名称 下拉框得到焦点
    const changeq1 = () => {
      dataForm.rawName = ''
      dataForm.batch = ''
      dataForm.supplierName = ''
      dataForm.yarnCard = ''
      dataForm.colourNumber = ''
      dataForm.colorName = ''
      dataForm.unit = ''
      dataForm.customName = ''
      let list: any = dataForm.nameList1.filter(function (o: any) {
        return o['yarnCode'] == dataForm.rawCode
      })
      if (list.length > 0) {
        dataForm.rawName = list[0]['yarnName']
        dataForm.rawCode = list[0]['yarnCode']
        dataForm.batch = list[0]['productionBatch']
        dataForm.supplierName = list[0]['supplier']
        dataForm.yarnCard = list[0]['yarnBrand']
        dataForm.colourNumber = list[0]['colorCode']
        dataForm.colorName = list[0]['colorName']
        dataForm.unit = list[0]['unit']
        dataForm.clientName = list[0]['customName']
        dataForm.level = list[0]['level']
        pageData.pieceWeight1 = list[0]['pieceWeight']
        listOb.list.forEach(function (o: any) {
          o['toHeavyKg'] = list[0]['pieceWeight']
          o.toHeavyPound = parseFloat((o['toHeavyKg'] * 2.20462262185).toFixed(2))
        })
      }
    }
    const changeq2 = () => {
      dataForm.rawCode = ''
      dataForm.batch = ''
      dataForm.supplierName = ''
      dataForm.yarnCard = ''
      dataForm.colourNumber = ''
      dataForm.colorName = ''
      dataForm.unit = ''
      dataForm.customName = ''
      let list: any = dataForm.nameList1.filter(function (o: any) {
        return o['yarnName'] == dataForm.rawName
      })
      if (list.length > 0) {
        dataForm['rawName'] = list[0]['yarnName']
        dataForm['rawCode'] = list[0]['yarnCode']
        dataForm.batch = list[0]['productionBatch']
        dataForm.supplierName = list[0]['supplier']
        dataForm.yarnCard = list[0]['yarnBrand']
        dataForm.colourNumber = list[0]['colorCode']
        dataForm.colorName = list[0]['colorName']
        dataForm.unit = list[0]['unit']
        dataForm.clientName = list[0]['customName']
        dataForm.level = list[0]['level']
        pageData.pieceWeight1 = list[0]['pieceWeight']
        listOb.list.forEach(function (o: any) {
          o['toHeavyKg'] = list[0]['pieceWeight']
          o.toHeavyPound = parseFloat((o['toHeavyKg'] * 2.20462262185).toFixed(2))
        })
      }
    }
    const focusSelp = () => {
      selCxAllp({
        in_stock_number: dataForm.sourceOdd,
        warehouse_id: dataForm.warehouseId,
        yarn_code: '',
        queryFields:
          'yarn_code,yarn_name,production_batch,supplier,yarn_brand,color_code,color_name,unit,custom_name,piece_weight,level',
      })
    }
    const focusSelp1 = () => {
      selCxAllp({
        in_stock_number: dataForm.sourceOdd,
        warehouse_id: dataForm.warehouseId,
        yarn_name: '',
        queryFields:
          'yarn_code,yarn_name,production_batch,supplier,yarn_brand,color_code,color_name,unit,custom_name,piece_weight,level',
      })
    }

    const handleSearchp = (value: any) => {
      if (value) {
        const ob = {
          yarn_code: value,
          warehouse_id: dataForm.warehouseId,
          in_stock_number: dataForm.sourceOdd,
          queryFields:
            'yarn_code,yarn_name,production_batch,supplier,yarn_brand,color_code,color_name,unit,custom_name,piece_weight,level',
        }
        loading.value = true
        selCxAllp(ob)
        options.value = dataForm.nameList1
        loading.value = false
      } else {
        options.value = []
      }
    }
    const handleSearchp1 = (value: any) => {
      if (value) {
        const ob = {
          yarn_name: value,
          warehouse_id: dataForm.warehouseId,
          orderNo: dataForm.sourceOdd,
          queryFields:
            'yarn_code,yarn_name,production_batch,supplier,yarn_brand,color_code,color_name,unit,custom_name,piece_weight,level',
        }
        loading.value = true
        selCxAllp(ob)
        options.value = dataForm.nameList1
        loading.value = false
      } else {
        options.value = []
      }
    }
    const selCxAllp = (val: any): void => {
      post({
        url: 'wms/yarnInStock/getInStockNumberList',
        data: val,
      }).then(({ code, data }) => {
        if (code === 200) {
          dataForm.nameList1 = data
        }
      })
    }

    const localeText1: any = ref(localeText)
    const huiche = () => {
      pagination.page = 1
      doRefresh()
    }
    const clearsource = () => {
      dataForm.rawCode = ''
      dataForm.rawName = ''
    }
    const changeSoure = () => {
      dataForm.rawCode = ''
      dataForm.rawName = ''
    }
    const pagingList1: any = ref(pagingList)
    //打印预览PDF
    const printPdf = (e: any) => {
      post({
        url: 'qms/stockSmokePounds/printFabric',
        data: e,
        responseType: 'blob'
      }).then((res: any) => {
        let reader: any = new FileReader();
        reader.readAsDataURL(res);
        reader.onload = function () {
          let pdfBase64 = reader.result.replace('data:application/pdf;base64,', '');
          printJS({ printable: pdfBase64, type: 'pdf', base64: true })
        };
      });

    }

    const { saveGridState: saveGridState01, updateGridState: updateGridState01 } = saveOrUpdateGridState01('RawMaterialWeighingRecord', gridOption, colState, tc)
    const onColumnMoved = () => {
      saveGridState01()
    }
    const onColumnResized = () => {
      saveGridState01()
    }
    const onColumnVisible = () => {
      saveGridState01()
    }
    return {
      saveOrUpdateGridState01,
      saveGridState01,
      updateGridState01,
      onColumnMoved,
      onColumnResized,
      onColumnVisible,
      colState,
      changeSoure,
      clearsource,
      pagingList1,
      huiche,
      localeText1,
      changeq1,
      changeq2,
      handleSearchp,
      handleSearchp1,
      focusSelp,
      focusSelp1,
      selCxAllp,
      focusSel9,
      handleSearch9,
      selCxAll9,
      companyListof,
      // computeList,
      whList,
      searchData,
      companyList,
      whTypeList,
      companyChange,
      changeSourceOdd,
      focusSelSourceOdd,
      handleSearchSourceOdd,
      poundChange,
      defaultColDef,
      tc,
      gridOption,
      gridReady,
      total,
      headerShow,
      dayjs,
      scroll,
      scrollbar,
      tablediv,
      hasChiese,
      deleteHandler,
      sideOk,
      formRef,
      dataForm,
      addHandler,
      selectedRowKeys,
      pagination,
      tableColumns,
      table,
      rowKey,
      pageData,
      editHandler,
      selectHandler,
      inputBlur,
      isChiese,
      exports,
      options,
      loading,
      handleSearch,
      focusSel,
      options1,
      loading1,
      handleSearch1,
      focusSel1,
      visible,
      handleClick,
      handleBeforeOk,
      handleCancel,
      tableColumnsCf,
      s: selectedRowKeysCf.selectedRowKeys,
      addLine,
      delLine,
      listOb,
      corporateRef,
      corporateChange,
      getCorporateList,
      changeCose,
      focusunit,
      searchUnit,
      getUnitList,
      PageSize,
      change1,
    }
  },
  components: { Toolbar,  },
}
</script>
<style scoped lang="less">
#Table td,
#Table th {
  border: 1px solid #ccc;
  padding: 0 10px 0 10px;
  border-right: 1px solid #dde2eb;
}

.input-demo bacClass {
  border-right: 1px solid #dde2eb;
}

.input-demo {
  border-right: 1px solid #dde2eb;
}

.bacColor {
  background-color: #f53f3f !important;
}
</style>
